package org.tiger.springboot.redis.util;

import com.google.common.collect.Maps;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtobufIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 序列化工具
 */
public class SerializerUtil {

    private final static Logger logger = LoggerFactory.getLogger(SerializerUtil.class);

    /**
     * schema缓存
     */
    private static Map<Class<?> ,Schema<?>> schemaMap = Maps.newConcurrentMap();

    /**
     * 获取schema
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> Schema<T> getSchema(Class<T> clazz){

        if(schemaMap.containsKey(clazz)){
            return (Schema<T>) schemaMap.get(clazz);
        }
        Schema<T> schema = RuntimeSchema.getSchema(clazz);
        schemaMap.put(clazz,schema);
        return schema;
    }


    /**
     * 对象序列化
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> byte[] objToByte(T obj){
        Class<T> clazz = (Class<T>) obj.getClass();
        LinkedBuffer linkedBuffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            return ProtobufIOUtil.toByteArray(obj,getSchema(clazz),linkedBuffer);
        }catch (Exception e){
            logger.error("serialize obj error : ",e);
        }finally {
            linkedBuffer.clear();
        }
        return null;
    }

    /**
     * 反序列化
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T byteToObj(byte[] data,Class<T> clazz){
        try {
            T obj = clazz.newInstance();
            Schema<T> schema = getSchema(clazz);
        }catch (Exception e){
            logger.error("serialize to obj error : ",e);
        }

        return null;
    }

}
